/**
 * Copyright &copy; 2020 <a href="https://github.com/somowhere/exam-system">exam-system</a> All rights reserved.
 */
package com.shanhesoft.java.modules.exam.web;


import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.ApiOperation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanhesoft.java.common.core.config.ApplicationConfig;
import com.shanhesoft.java.common.core.constant.CommonConstants;
import com.shanhesoft.java.common.core.util.FileUtil;
import com.shanhesoft.java.common.core.util.Result;
import com.shanhesoft.java.common.core.util.StringUtil;
import com.shanhesoft.java.common.core.vo.PageModel;
import com.shanhesoft.java.common.data.util.QueryWrapperUtil;
import com.shanhesoft.java.common.log.annotation.LogOperate;
import com.shanhesoft.java.common.log.enums.BusinessType;
import com.shanhesoft.java.common.web.resource.BaseResource;
import com.shanhesoft.java.modules.exam.domain.dto.VirtualTrainingDetailInstanceDto;
import com.shanhesoft.java.modules.exam.domain.dto.VirtualTrainingDetailInstanceQueryCriteria;
import com.shanhesoft.java.modules.exam.domain.vo.BankVirtualTrainingQueVo;
import com.shanhesoft.java.modules.exam.domain.vo.VirtualTrainingDetailInstanceVo;
import com.shanhesoft.java.modules.exam.service.BankVirtualTrainingQueService;
import com.shanhesoft.java.modules.exam.service.VirtualTrainingDetailInstanceService;
import com.shanhesoft.java.modules.sys.domain.vo.UserVo;
import com.shanhesoft.java.modules.sys.service.UserService;

import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.util.Map;
import java.util.Set;

/**
 * 课程实训题目实例管理Controller 课程实训题目实例管理
 * @author admin
 * @version 2020-11-17 01:04:34
 */
@RestController
@RequestMapping(value = "${application.admin-path}/exam/virtualTrainingDetailInstance")
@Slf4j
@AllArgsConstructor
public class VirtualTrainingDetailInstanceResource extends BaseResource {

	private final VirtualTrainingDetailInstanceService service;
	private final UserService userService;
	private final BankVirtualTrainingQueService bankVirtualTrainingQueService;

	/**
	 * @param id
	 * @return
	 */
	@GetMapping(CommonConstants.URL_ID_REGEX)
	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	public Result get(@PathVariable String id) {
		log.debug("REST request to get Entity : {}", id);
		return  Result.buildOkData(service.findVoById(id));
	}
	/**
	 * GET / : get all virtualTrainingDetailInstance.
	 *
	 * @param pm the pagination information
	 * @return the Result with status 200 (OK) and with body all virtualTrainingDetailInstance
	 */

	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@GetMapping
	@ApiOperation(value = "课程实训题目实例管理查看")
	public Result getPage(PageModel pm, VirtualTrainingDetailInstanceQueryCriteria virtualTrainingDetailInstanceQueryCriteria) {
		QueryWrapper wrapper = QueryWrapperUtil.getWrapper(pm, virtualTrainingDetailInstanceQueryCriteria);
		return Result.buildOkData(service.findPage(pm, wrapper));
	}

	/**
	 * POST / : Save a virtualTrainingDetailInstanceDto.
	 *
	 * @param virtualTrainingDetailInstanceDto the HTTP virtualTrainingDetailInstance
	 */
	@PreAuthorize("@pms.hasPermission('exam_trainingInstance_edit')")
	@ApiOperation(value = "课程实训题目实例管理编辑")
	@PostMapping
	public Result save(@Valid @RequestBody VirtualTrainingDetailInstanceDto virtualTrainingDetailInstanceDto) {
		log.debug("REST request to save VirtualTrainingDetailInstanceDto : {}", virtualTrainingDetailInstanceDto);
		service.saveOrUpdate(virtualTrainingDetailInstanceDto);
		return Result.buildOk("保存课程实训题目实例管理成功");

	}

	@ApiOperation(value = "课程实训题目实例管理--保存并返回对象")
	@PostMapping("/saveReturn")
	public Result saveReturn(@Valid @RequestBody VirtualTrainingDetailInstanceDto virtualTrainingDetailInstanceDto) {
		log.debug("REST request to save VirtualTrainingDetailInstanceDto : {}", virtualTrainingDetailInstanceDto);
		return Result.buildOkData(service.saveOrUpdateReturn(virtualTrainingDetailInstanceDto));

	}

	/**
	 * DELETE //:ids : delete the "ids" VirtualTrainingDetailInstance.
	 *
	 * @param ids the id of the virtualTrainingDetailInstance to delete
	 * @return the Result with status 200 (OK)
	 */
	@PreAuthorize("@pms.hasPermission('exam_trainingInstance_del')")
	@ApiOperation(value = "课程实训题目实例管理删除")
	@DeleteMapping
	public Result delete(@RequestBody Set<String> ids) {
		log.debug("REST request to delete VirtualTrainingDetailInstance: {}", ids);
		service.removeByIds(ids);
		return Result.buildOk("删除课程实训题目实例管理成功");
	}

	@GetMapping("/getUserList")
	@ApiOperation(value = "查看正确答题人列表")
	public Result getUserList(PageModel pm, VirtualTrainingDetailInstanceQueryCriteria virtualTrainingDetailInstanceQueryCriteria) {
		return Result.buildOkData(service.getUserList(pm, virtualTrainingDetailInstanceQueryCriteria));
	}

	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@ApiOperation(value = "启动试验环境")
	@PostMapping("startVirtualEnv")
	public Result startVirtualEnv(@Valid @RequestBody VirtualTrainingDetailInstanceDto virtualTrainingDetailInstanceDto) {
		return service.startVirtualEnv(virtualTrainingDetailInstanceDto);
	}

	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@ApiOperation(value = "停止试验环境")
	@PostMapping("stopVirtualEnv")
	public Result stopVirtualEnv(@Valid @RequestBody VirtualTrainingDetailInstanceDto virtualTrainingDetailInstanceDto) {
		return service.stopVirtualEnv(virtualTrainingDetailInstanceDto);
	}

	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@ApiOperation(value = "删除试验环境")
	@PostMapping("deleteVirtualEnv")
	public Result deleteVirtualEnv(@Valid @RequestBody VirtualTrainingDetailInstanceDto virtualTrainingDetailInstanceDto) {
		return service.deleteVirtualEnv(virtualTrainingDetailInstanceDto);
	}

	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@ApiOperation(value = "试验延时")
	@PostMapping("delayed")
	public Result delayed(@RequestBody Map<String, String> delayed) {
		return service .delayed(delayed.get("TrainingDetailInstanceId"), Integer.valueOf(delayed.get("time")));
	}

	/**
	 * 通用下载请求
	 *
	 * @param TrainingDetailInstanceId 实训实例编号
	 */
	//@PreAuthorize("@pms.hasPermission('exam_trainingInstance_view')")
	@GetMapping("/download")
	public void fileDownload(String TrainingDetailInstanceId, HttpServletResponse response, HttpServletRequest request) {
		try {
			if(StringUtil.isEmpty(TrainingDetailInstanceId)) {
				throw new Exception("实训实例编号不能为空！ ");
			}
			VirtualTrainingDetailInstanceVo trainingDetailInstanceVo = service.findVoById(TrainingDetailInstanceId);
			String material = trainingDetailInstanceVo.getMaterial();
			UserVo userVo = userService.findUserVoById(trainingDetailInstanceVo.getUserId());
			String nickname = userVo.getNickname();
			String username = userVo.getUsername();
			BankVirtualTrainingQueVo virtualTrainingQueVo = bankVirtualTrainingQueService.findVoById(trainingDetailInstanceVo.getTrainQueId());
			String title = virtualTrainingQueVo.getTitle();
			String realFileName = "";
			if(StringUtil.isNotEmpty(nickname)) {
				realFileName = nickname+"_"+title+".zip";
			}else {
				realFileName = username+"_"+title+".zip";
			}
			String filePath = ApplicationConfig.getDownloadPath()+StringUtil.SLASH+ realFileName;
			FileUtil.compress(material, filePath);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition",
				"attachment;fileName=" + FileUtil.setFileDownloadHeader(request, realFileName));
			FileUtil.writeBytes(filePath, response.getOutputStream());
			FileUtil.deleteFile(filePath);
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}
	}
}
